﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using Warehouse_Management.Single;

namespace Warehouse_Management.New
{
    public partial class frmPhieuGiaoDich : DevExpress.XtraEditors.XtraForm
    {
        public frmPhieuGiaoDich()
        {
            InitializeComponent();
        }
        public PhieuGD PGD;
        private List<PhieuGDChiTiet> ListHangDelete = new List<PhieuGDChiTiet>();
        private void frmPhieuGiaoDich_Load(object sender, EventArgs e)
        {
            DisplayForm();
            LoadDuLieu();
        }
        private void LoadDuLieu()
        {
            if (PGD == null)
            {
                PGD = new PhieuGD();
                PGD.HangCollection = new List<PhieuGDChiTiet>();
                PGD.TaoMaPhieuMoi((TrangThaiChungTu)this.Tag == TrangThaiChungTu.PhieuNhap ? 'N' : 'X',khoUC1.MaKho);
                txtMaPhieu.Text = PGD.MaPhieu;
                dateNgayNhap.EditValue = DateTime.Today;
            }
            else
            {
                txtGhiChu.Text = PGD.GhiChu;
                txtMaPhieu.Text = PGD.MaPhieu;
                khoUC1.MaKho = PGD.MaKho;
                dateNgayNhap.EditValue = PGD.NgayNhap;
                PGD.LoadHangCollection();
                gridControl1.DataSource = PGD.HangCollection;
            }
        }
        private void get()
        {
            if (PGD != null)
            {
                // PGD.MaPhieu = txtMaPhieu.Text ;
                PGD.GhiChu = txtGhiChu.Text;
                PGD.NgayNhap = System.Convert.ToDateTime(dateNgayNhap.EditValue);
                PGD.MaKho = khoUC1.MaKho;
            }
        }
        private void DisplayForm()
        {
            switch ((TrangThaiChungTu)this.Tag)
            {
                case TrangThaiChungTu.PhieuNhap:
                    btnSelectHang.ForeColor = Color.Green;
                    txtMaPhieu.BackColor = Color.Green;
                    gridView1.Columns["isHangTra"].Visible = false;
                    break;
                case TrangThaiChungTu.PhieuXuat:
                    btnSelectHang.ForeColor = Color.Red;
                    txtMaPhieu.BackColor = Color.Red;
                    
                    break;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSelectHang_Click(object sender, EventArgs e)
        {
            listHang f = new listHang();
            f.ShowDialog(this);
            List<PhieuGDChiTiet> listhang = new List<PhieuGDChiTiet>();
            listhang = f.listChiTiet;
            if (listhang != null && listhang.Count > 0)
            {
                foreach (PhieuGDChiTiet hangGd in listhang)
                {
                    if (!isExit(hangGd.Barcode))
                        PGD.HangCollection.Add(hangGd);
                }
                gridControl1.DataSource = PGD.HangCollection;
                gridControl1.Refresh();
                gridView1.RefreshData();
            }
                
        }
        private bool isExit(string barcode)
        {
            foreach (PhieuGDChiTiet hangGd in PGD.HangCollection)
            {
                if (hangGd.Barcode.Trim() == barcode.Trim())
                    return true;
            }
            return false;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {   dxErrorProvider1.ClearErrors();
            bool isValid = true;
            if (string.IsNullOrEmpty(dateNgayNhap.Text))
            {
                dxErrorProvider1.SetError(dateNgayNhap, "Chọn kho hàng", ErrorType.Critical);
                isValid = false;
            }
            if (string.IsNullOrEmpty(khoUC1.MaKho))
            {
                dxErrorProvider1.SetError(khoUC1, "Phải nhập ngày tháng", ErrorType.Warning);
                isValid = false;
            }
            if (!isValid)
                return;
            if (PGD.HangCollection == null || PGD.HangCollection.Count == 0)
            {
                MessageBox.Show("Chưa nhập hàng !");
                return;
            }
            for (int i = 0; i < PGD.HangCollection.Count; i++)
            {
                if (PGD.HangCollection[i].DonGia == 0)
                {
                    MessageBox.Show("Đơn giá dòng hàng thứ " + i + " chưa được nhập");
                    isValid = false;
                    break;
                }
            }
            if (!isValid)
                return;
            get();
            string result = PGD.InsertUpdateFull();
            if (ListHangDelete.Count > 0)
                PhieuGDChiTiet.DeleteCollection(ListHangDelete);
            if (string.IsNullOrEmpty(result))
            {
                MessageBox.Show("Lưu thành công !");
                this.Close();
            }
            else
                MessageBox.Show("Lỗi khi lưu dữ liệu - Vui lòng kiểm tra lại\r\n" + result);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Lỗi khi lưu dữ liệu - Vui lòng kiểm tra lại\r\n" + ex.Message);
            }
         
            
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column == gridView1.Columns["SoLuong"] || e.Column == gridView1.Columns["DonGia"])
            {
                object DonGia = gridView1.GetRowCellValue(e.RowHandle,gridView1.Columns["DonGia"]);
                object SoLuong = gridView1.GetRowCellValue(e.RowHandle,gridView1.Columns["SoLuong"]);
                object ThanhTien = ((decimal)DonGia) * ((decimal)SoLuong);
                gridView1.SetRowCellValue(e.RowHandle,gridView1.Columns["ThanhTien"],ThanhTien);
            }
        }

        

        private void gridView1_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {
            string t = e.Item.ToString();
            
             decimal TongTien = 0;
             for (int i = 0; i < gridView1.RowCount; i++)
             {
                 bool isHangTra = (bool)gridView1.GetRowCellValue(i, "isHangTra");
                 if (!isHangTra)
                 {
                     TongTien += (decimal)gridView1.GetRowCellValue(i, "ThanhTien");
                 }
             }
             e.TotalValue = TongTien;
             PGD.TongTien = TongTien;
        }

        private void btnXoaHang_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có chắc chắc muốn xóa các dòng hàng này? ", "", MessageBoxButtons.YesNo) == DialogResult.No)
                return;
            int[] selected = gridView1.GetSelectedRows();
            List<PhieuGDChiTiet> listdelete = new List<PhieuGDChiTiet>();
            foreach (int i in selected)
            {
                PhieuGDChiTiet hang = (PhieuGDChiTiet)gridView1.GetRow(i);
                if (hang != null)
                    listdelete.Add(hang);
            }
            foreach (PhieuGDChiTiet hang in listdelete)
            {
                this.PGD.HangCollection.Remove(hang);
                if (hang.ID != 0)
                    ListHangDelete.Add(hang);


            }
            gridControl1.Refresh();
            gridView1.RefreshData();
        } 
    }
}